package com.example.yangjintingtest.mapper;

import com.example.yangjintingtest.domain.BlogArticle;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface BlogArticleMapper {
    // 根据id查询文章信息
    @Select("SELECT * FROM t_article WHERE id=#{id}")
    public BlogArticle selectArticleWithId(Integer id);

    // 发表文章,同时使用@Options注解获取自动生成的主键id
    @Insert("INSERT INTO t_article (title,created,modified,tags,categories," +
            "allow_comment,thumbnail,content)" +
            "VALUES (#{title},#{created},#{modified},#{tags},#{categories}," +
            "#{allowComment},#{thumbnail},#{content})")
    @Options(useGeneratedKeys=true, keyProperty="id", keyColumn="id")
    public Integer publishArticle(BlogArticle article);

    // 文章分页查询
    @Select("SELECT * FROM t_article ORDER BY id DESC")
    public List<BlogArticle> selectArticleWithPage();

    // 通过id删除文章
    @Delete("DELETE FROM t_article WHERE id=#{id}")
    public void deleteArticleWithId(int id);

    // 站点业务统计, 统计文章数量
    @Select("SELECT COUNT(*) FROM t_article")
    public Integer countArticle();

    // 通过id更新文章
//    @Update("UPDATE t_article SET title=#{title},created=#{created},modified=#{modified},tags = #{tags}, thumbnail = #{thumbnail}, content = #{content}," +
//            "categories = #{categories}, hits = #{hits},comments_num = #{commentNum}, allow_comment = #{allowComment} WHERE id=#{id}")
    @Update({
            "<script>",
            "UPDATE t_article",
            "<set>",
            "<if test='title != null'>title = #{title},</if>",
            "<if test='content != null'>content = #{content},</if>",
            "<if test='created != null'>created = #{created},</if>",
            "<if test='categories != null'>categories = #{categories},</if>",
            "<if test='tags != null'>tags = #{tags},</if>",
            "<if test='allowComment != null'>allow_comment = #{allowComment},</if>",
            "<if test='thumbnail != null'>thumbnail = #{thumbnail},</if>",
            "modified = CURRENT_TIMESTAMP, ",
            "</set>",
            "WHERE id = #{id}",
            "</script>"
    })
    public Integer updateArticleWithId(BlogArticle article);
}
